package stringutil

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"
	"crypto/md5"
	"crypto/sha512"
	"encoding/hex"
	"fmt"
)

func CryptPassword(pwd, salt string) string {
	s := sha512.New()
	s.Write([]byte(pwd + salt))
	return fmt.Sprintf("%x", s.Sum([]byte("")))
}

func HashBankcard(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}

// 3DES加密
func TripleDesEncrypt(origData, des3key []byte) ([]byte, error) {
	block, err := des.NewTripleDESCipher(des3key)
	if err != nil {
		return nil, err
	}
	origData = PKCS5Padding(origData, block.BlockSize())
	// origData = ZeroPadding(origData, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, des3key[:8])
	crypt := make([]byte, len(origData))
	blockMode.CryptBlocks(crypt, origData)
	return crypt, nil
}

// 3DES解密
func TripleDesDecrypt(crypt, des3key []byte) ([]byte, error) {
	block, err := des.NewTripleDESCipher(des3key)
	if err != nil {
		return nil, err
	}
	blockMode := cipher.NewCBCDecrypter(block, des3key[:8])
	origData := make([]byte, len(crypt))
	// origData := crypt
	blockMode.CryptBlocks(origData, crypt)
	origData = PKCS5UnPadding(origData)
	// origData = ZeroUnPadding(origData)
	return origData, nil
}

func PKCS5Padding(text []byte, blockSize int) []byte {
	padding := blockSize - len(text)%blockSize
	pad := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(text, pad...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后⼀一个字节 unPadding 次
	un := int(origData[length-1])
	return origData[:(length - un)]
}
